package com.bsoft.gol.hcs.his.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hcs.his.bean.request.DeptLeaderListRequest;
import com.bsoft.gol.hcs.his.bean.response.DeptLeaderListRepHisBean;
import hcn.util.BaseResponse;
import hcn.util.ResultCode;
import com.bsoft.gol.hcs.his.bean.request.QueryPatientInfoRequest;
import com.bsoft.gol.hcs.his.bean.request.SearchDocumentRequest;
import com.bsoft.gol.hcs.his.bean.response.QueryPatientInfoResponse;
import com.bsoft.gol.hcs.his.bean.response.SearchDocumentResponse;
import com.bsoft.gol.hcs.his.service.IPatientHisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.bsoft.gol.hcs.specialist.bean.request.PatientRequest;
import com.bsoft.gol.hcs.specialist.bean.response.PatientResponse;
import com.bsoft.gol.hcs.utils.*;
import org.atag.util.http.KdHttpClientUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: his服务
 * @Author: zhaorb
 * @Date: 2020/6/4 15:08
 **/
@Service
public class PatientHisServiceImpl implements IPatientHisService {
    private final static Logger log = LoggerFactory.getLogger(PatientHisServiceImpl.class);


    @Override
    public BaseResponse<PatientResponse> listPatient(PatientRequest request) {
        log.info("PatientHisServiceImpl.listPatient 入参：{}", request);
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(Constants.HIS_CLIENT_URL_01
                + Constants.OUTPATIENT_LIST_PATIENT, jsonParams);
        log.info("PatientHisServiceImpl.listPatient 第三方返回数据:{}", jsonObject);
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null) {
                PatientResponse response = JSONObject.parseObject(
                        jsonObject.get("data").toString(), PatientResponse.class);
                log.info("PatientHisServiceImpl.listPatient 出参：{}", response);
                return BaseRespUtil.setResultSuccess(response);
            } else {
                return BaseRespUtil.setResultError(jsonObject.getString("message"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return BaseRespUtil.setResultError(null);
        }
    }

    /**
     * 患者信息查询
     *
     * @param request
     * @return org.atag.core.base.BaseResponse<his.bean.response.QueryPatientInfoResponse>
     * @throws
     * @author tongtp
     * @date 2021/8/6 15:01
     */
    @Override
    public BaseResponse<QueryPatientInfoResponse> queryPatientInfoList(QueryPatientInfoRequest request) {
        log.info("PatientHisServiceImpl.queryPatientInfoList 入参：{}", JSONObject.toJSON(request));
        BaseResponse<QueryPatientInfoResponse> result = new BaseResponse<>();

        Map<String, Object> map = new HashMap<>();
        map.put("serviceName", "HCICInvoke");
        map.put("inParm", getParamString("/patient/queryPatientInfoList", JSONObject.toJSON(request).toString()));

//        String s = transApiService.transService(map);
//        log.info("PatientHisServiceImpl.queryPatientInfoList原始回参{}", s);
//        JSONObject object = JSON.parseObject(s);
//        String result2 = object.getString("result");

        org.json.JSONObject jsonObject1 = null;
        try {
//            jsonObject1 = XML.toJSONObject(result2);
            org.json.JSONObject bsXml = jsonObject1.getJSONObject("BSXml");
            org.json.JSONObject msgHeader = bsXml.getJSONObject("MsgHeader");
            String detail = msgHeader.getString("Detail");
            JSONObject jsonObject = JSONObject.parseObject(detail);
            log.info("queryPatientInfoList 第三方返回数据：{}", JSONObject.toJSONString(jsonObject));
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null) {
                JSONObject data = JSONObject.parseObject(jsonObject.get("data").toString());
                List<QueryPatientInfoResponse.PatientInfo> patientInfoList = JSONObject.parseArray(
                        data.get("patientInfoList").toString(), QueryPatientInfoResponse.PatientInfo.class);
                QueryPatientInfoResponse response = new QueryPatientInfoResponse();
                List<QueryPatientInfoResponse.PatientInfo> patientList = new ArrayList<>();
                response.setPatientInfoList(patientInfoList);
                response.setTotal(data.getLong("total"));

                result.setCode(ResultCode.SUCCESS);
                result.setData(response);
            } else {
                result.setCode(jsonObject.getInteger("code"));
                result.setMessage(jsonObject.getString("message"));
            }

        } catch (Exception e) {
//            log.error("PatientHisServiceImpl.queryPatientInfoList数据转换错误 :{}", s);
        }
        return result;
    }

    @Override
    public BaseResponse<SearchDocumentResponse> querySearchDocument(SearchDocumentRequest request) {

        BaseResponse<SearchDocumentResponse> baseResponse = new BaseResponse<>();

        String req = "<BSXml>" +
                "<MsgHeader>" +
                "<Sender>HOL</Sender>" +
                "<MsgType>HIS_IH_1201</MsgType>" +
                "<MsgVersion>3.0</MsgVersion>" +
                "</MsgHeader>" +
                "<Param>" +
                "<startTime>" + request.getStartTime() + "</startTime>" +
                "<endTime>" + request.getEndTime() + "</endTime>" +
                "<documentType>" + request.getDocumentType() + "</documentType>" +
                "<keywords>" + request.getKeywords() + "</keywords>" +
                "<sortType>1</sortType>" +
                "<pageNo>1</pageNo>" +
                "<pageSize>9999</pageSize>" +
                "</Param>" +
                "</BSXml>";

        Map<String, Object> map = new HashMap<>();
        map.put("serviceName", "SearchDocument");
        map.put("inParm", req);
        log.info("PatientHisServiceImpl.querySearchDocument 入参回参{}", map);
//        String s = transApiService.transService(map);
//        log.info("PatientHisServiceImpl.querySearchDocument 原始回参{}", s);
//        JSONObject object = JSON.parseObject(s);
//        String result2 = object.getString("result");

//        if (CommonUtils.isEmpty(result2)) {
//            baseResponse.setCode(ResultCode.ERROR);
//            baseResponse.setMessage("请求失败");
//            return baseResponse;
//
//        }
//        SearchDocumentResponse searchDocumentResponse = JAXBUtils.xml2Object(result2, SearchDocumentResponse.class);

//        if (CommonUtils.isNotEmpty(searchDocumentResponse)) {
//            baseResponse.setCode(searchDocumentResponse.getCode());
//            baseResponse.setMessage(searchDocumentResponse.getMessage());
//            baseResponse.setData(searchDocumentResponse);
//        }else {
//            baseResponse.setCode(ResultCode.ERROR);
//            baseResponse.setMessage("请求失败");
//        }

        return baseResponse;
    }


    /**
     * @describe  获取科室负责人
     */
    public DeptLeaderListRepHisBean queryDeptLeaderList(DeptLeaderListRequest request){
        log.info("=获取科室负责人：入参={}", JSONObject.toJSONString(request));
        JSONObject jsonParams=(JSONObject) JSONObject.toJSON(request);
        jsonParams.put("organizationId", "2003");
        jsonParams.put("funcode", "ODS_DeptLeaderList");
        //请求接口
        log.info("入参-----------------接口"+jsonParams);
        JSONObject json=   WebServiceUtil.openWSDL2(null, XmlToJson.getXML2(jsonParams.toString()));
        log.info("=获取科室负责人：出参={}", json);
        try{
            DeptLeaderListRepHisBean dataVo = JSONObject.parseObject(json.getJSONObject("Data").toJSONString(),DeptLeaderListRepHisBean.class);
            return dataVo;
        }catch (Exception e){
            log.error("获取科室负责人失败"+e.getMessage());
        }
        return null;
    }

    private static String getParamString(String interfaceName, String data) {
        return "<BSXml>\n" +
                "<MsgHeader>\n" +
                "<Sender>SF</Sender>\n" +
                "<MsgType>HIS_IH_9001</MsgType>\n" +
                "<MsgVersion>3.0</MsgVersion>\n" +
                "</MsgHeader>\n" +
                "<Param>\n" +
                "<InterfaceName>" + interfaceName + "</InterfaceName>\n" +
                "<Data><![CDATA[" + data + "]]></Data>\n" +
                "</Param>\n" +
                "</BSXml>";
    }
}
